package cn.song.exception;

import cn.song.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLSyntaxErrorException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import static cn.song.common.R.failed;

/**
 * 全局异常处理
 *
 * @author Song~
 * @since 2024-07-20 14:02:13
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 异常处理方法
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.error("自定义异常:{}", ex.toString(), ex);
        return R.error(ex.getMessage());
    }
    /**
     * 异常处理程序
     *
     * @param e e
     * @return {@link R }
     * @date 2024/04/04
     * @author SongRenShuo
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R handlerHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("请求方式错误：", e);
        return failed("请求方式错误：" + e.getMessage());
    }

    /**
     * 异常处理程序
     *
     * @param e e
     * @return {@link R }
     * @date 2024/04/04
     * @author SongRenShuo
     */
    @ExceptionHandler(BadSqlGrammarException.class)
    public R handlerSQLException(BadSqlGrammarException  e) {
        String msg = "";
        Throwable cause = e.getCause();
        if (cause instanceof SQLIntegrityConstraintViolationException) {
            msg = "数据插入失败，可能违反了完整性约束";
        } else if (cause instanceof SQLSyntaxErrorException) {
            msg = "SQL语句语法错误";
        }

        log.error("数据库操作错误：{}", msg, e);
        return failed("数据库错误,请联系管理员");
    }

    /**
     * 异常处理程序
     *
     * @param e e
     * @return {@link R }
     * @date 2024/04/04
     * @author SongRenShuo
     */
    @ExceptionHandler(BindException.class)
    public R handlerBindException(BindException e) {
        log.error("请求参数格式有误：", e);
        List<ObjectError> objectErrorList = e.getAllErrors();
        List<String> errorMessageList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(objectErrorList)) {
            // 错误非空
            for (ObjectError error : objectErrorList) {
                errorMessageList.add(error.getDefaultMessage());
            }
        }
        return failed("请求参数格式有误：" + errorMessageList);
    }


    /**
     * 异常处理程序
     *
     * @param e e
     * @return {@link R }
     * @date 2024/04/04
     * @author SongRenShuo
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public R handlerMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        // 如果是HttpMessageNotReadableException，也可能是由于日期转换失败导致的
        if (e.getCause() instanceof MethodArgumentTypeMismatchException) {
            MethodArgumentTypeMismatchException nestedException = (MethodArgumentTypeMismatchException) e.getCause();
            log.error("请求参数类型不匹配（嵌套）：", nestedException);
            return failed("请求参数类型不匹配（嵌套）：无法将值 " + nestedException.getValue() + " 转换为类型 " + Objects.requireNonNull(nestedException.getRequiredType()).getSimpleName());
        }
        log.error("请求参数类型不匹配：", e);
        return failed("请求参数类型不匹配：无法将值 " + e.getValue() + " 转换为类型 " + Objects.requireNonNull(e.getRequiredType()).getSimpleName());

    }

    /**
     * 异常处理程序
     *
     * @param e e
     * @return {@link R }
     * @date 2024/04/04
     * @author SongRenShuo
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R handlerConstraintViolationException(ConstraintViolationException e) {
        // 校验框架 - violation
        StringBuilder errorMessage = new StringBuilder("请求参数错误：");
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            String messageTemplate = violation.getMessageTemplate();
            // // 大多数情况下错误信息会包含冒号分隔的字段名和错误描述
            if (messageTemplate.contains(":")) {
                errorMessage.append(violation.getMessage().split(":")[1].trim()).append(", ");
            } else {
                errorMessage.append(violation.getMessage()).append(" ");
            }
        }
        // 去除最后一个逗号和空格
        errorMessage.setLength(errorMessage.length());
        log.error("请求参数错误：{}", errorMessage, e);
        return failed(errorMessage.toString());
    }

    /**
     * 异常处理程序
     *
     * @param e e
     * @return {@link R }
     * @date 2024/04/04
     * @author SongRenShuo
     */
    @ExceptionHandler(Exception.class)
    public R handlerException(Exception e) {
        log.error("公共类错误：", e);
        return failed("操作失败：" + e.getMessage());
    }

}
